package com.ourygo.fileselect.util;

import java.io.File;

import com.feihua.dialogutils.util.DialogUtils;
import com.ourygo.fileselect.OurygoApplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Context;
import android.content.Intent;
import android.content.UriPermission;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.annotation.RequiresApi;
import androidx.documentfile.provider.DocumentFile;

/**
 * Create By feihua  On 2021/7/24
 */

public class FilePermissionUtil {
    public static final int REQUEST_CODE_FOR_DIR = 700;
    public static String root = Environment.getExternalStorageDirectory().getPath() + "/";
    public static String URI_ROOT_PREFIX="content://com.android.externalstorage"
            + ".documents/tree/primary%3AAndroid%2Fdata/document/primary%3A";

    public static String treeToPath(String path) {
        String path2 = "";
        if (path.contains("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary")) {
            path2 = path.replace("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A", root);
            path2 = path2.replace("%2F", "/");
        } else {
//            path2 = root + textUtils.getSubString(path + "测试", "document/primary%3A", "测试").replace("%2F", "/");

        }
        return path2;
    }

    //判断是否已经获取了Data权限，改改逻辑就能判断其他目录，懂得都懂
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isGrant(Context context) {
        for (UriPermission persistedUriPermission : context.getContentResolver().getPersistedUriPermissions()) {
            if (persistedUriPermission.isReadPermission() && persistedUriPermission.getUri().toString().equals("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata")) {
                return true;
            }
        }
        return false;
    }

    //直接返回DocumentFile
    public static DocumentFile getDocumentFile(Context context, String path) {
        return getDocumentFile(context, path, "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata");
    }

    //直接返回DocumentFile
    public static DocumentFile getDocumentFile(Context context, String path, String sdCardUri) {
        DocumentFile document = DocumentFile.fromTreeUri(context, Uri.parse(sdCardUri));
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        int start = path.indexOf("Android/");
        if (start == -1)
            start = path.indexOf("android/");
        if (start != -1)
            path = path.substring(start);
        String[] parts = path.split("/");
        for (int i = 2; i < parts.length; i++) {
            document = document.findFile(parts[i]);
        }
        return document;
    }

    //转换至uriTree的路径
    public static String changeToUri(String path) {
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        int start = path.indexOf("Android/");
        if (start == -1)
            start = path.indexOf("android/");
        if (start != -1)
            path = path.substring(start);

        String path2 = path.replace("/", "%2F");
        return "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" + path2;
    }

    //转换至uriTree的路径
    public static DocumentFile getDoucmentFile(Context context, String path) {
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        int start = path.indexOf("Android/");
        if (start == -1)
            start = path.indexOf("android/");
        if (start != -1)
            path = path.substring(start);
        String path2 = path.replace("/", "%2F");
        Log.e("FilePer", "Path为 " + path2);
        return DocumentFile.fromSingleUri(context, Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" + path2));
    }

    //转换至uriTree的路径
    public static String changeToUri2(String path) {
        String[] paths = path.replaceAll("/storage/emulated/0/Android/data", "").split("/");
        StringBuilder stringBuilder = new StringBuilder("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3AAndroid%2Fdata");
        for (String p : paths) {
            if (p.length() == 0) continue;
            stringBuilder.append("%2F").append(p);
        }
        return stringBuilder.toString();

    }

    //转换至uriTree的路径
    public static String changeToUri3(String path) {
        int start = path.indexOf("Android/");
        if (start == -1)
            start = path.indexOf("android/");
        if (start != -1)
            path = path.substring(start);
        if (path.endsWith("/"))
            path = path.substring(0, path.length() - 1);
        path = path.replace("/", "%2F");
        return ("content://com.android.externalstorage.documents/tree/primary%3A" + path);

    }

    //获取指定目录的权限
    public static void startFor(String path, Activity activity, int REQUEST_CODE_FOR_DIR) {
//        statusHolder.path = path;
        String uri = changeToUri(path);
        Uri parse = Uri.parse(uri);
        Intent intent = new Intent("android.intent.action.OPEN_DOCUMENT_TREE");
        intent.addFlags(
                Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, parse);
        }
        activity.startActivityForResult(intent, REQUEST_CODE_FOR_DIR);

    }

    //直接获取data权限，推荐使用这种方案
    public static void startForRoot(Activity activity, int REQUEST_CODE_FOR_DIR) {
        Uri uri1 = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata");
//        DocumentFile documentFile = DocumentFile.fromTreeUri(context, uri1);
        String uri = changeToUri(Environment.getExternalStorageDirectory().getPath());
        uri = uri + "/document/primary%3A" + Environment.getExternalStorageDirectory().getPath().replace("/storage/emulated/0/", "").replace("/", "%2F");
        Uri parse = Uri.parse(uri);
        DocumentFile documentFile = DocumentFile.fromTreeUri(activity, uri1);
        Intent intent1 = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent1.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        intent1.putExtra(DocumentsContract.EXTRA_INITIAL_URI, documentFile.getUri());
        activity.startActivityForResult(intent1, REQUEST_CODE_FOR_DIR);

    }

    /**
     * 路径是否需要data权限
     * @param path
     * @return
     */
    public static boolean isCheckFilePermission(String path) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q)
            if (path.contains("Android/data") || path.contains("android/data"))
                return true;
        return false;
    }

    public static DocumentFile createDir(Context activity,String path) {
        DocumentFile documentFile = getDocumentFile(activity, path);
        if (documentFile == null || !documentFile.isDirectory()) {
            return getDocumentFile(activity, FileUtil.getParentFilePath(path)).createDirectory(new File(path).getName());
        }
        return null;
    }

    public static DocumentFile createFile(Context activity,String filePath) {
        DocumentFile documentFile = getDocumentFile(activity, filePath);
        if (documentFile == null || !documentFile.exists()) {
            try {
                DocumentFile documentFile1 = getDocumentFile(activity,
                        FileUtil.getParentFilePath(filePath)).createFile("", new File(filePath).getName());
                if (documentFile1 == null) {
                    Log.e("FilePer", "失败空");
                } else {
                    Log.e("FilePer", "成功");
                }
                return documentFile;
            } catch (Exception e) {
                Log.e("FilePer", "失败错误" + e);
            }
        }
        return null;
    }

    /**
     * 是否有data路径的授权
     * @param activity
     * @param ygoPath
     * @param request
     * @return
     */
    public static boolean isDataPermissionAndRequest(Activity activity,String ygoPath, int request) {
        if (FilePermissionUtil.isCheckFilePermission(ygoPath)) {
            if (!FilePermissionUtil.isGrant(activity)) {
                DialogUtils dialogUtils = DialogUtils.getInstance(activity);
                View[] views = dialogUtils.dialogt("权限提示", "使用该功能需要授权data使用权限，点击“授权”进入授权界面后，直接点击底部“使用这个文件夹”即可完成授权。");
                Button b1, b2;
                b1 = (Button) views[0];
                b2 = (Button) views[1];
                b1.setText("取消");
                b2.setText("授权");
                b1.setOnClickListener(v -> dialogUtils.dis());
                b2.setOnClickListener(v -> {
                    dialogUtils.dis();
                    FilePermissionUtil.startForRoot(activity, request);
                });
                return false;
            }
        }
        return true;
    }

    @SuppressLint("WrongConstant")
    public static boolean isGetPermissionOk(Context context, Intent data) {
        if (data == null) {
            Utils.show("授权失败");
            return false;
        }
        Uri uri;
        if ((uri = data.getData()) != null) {
            context.getContentResolver().takePersistableUriPermission(uri, data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));//关键是这里，这个就是保存这个目录的访问权限
            Utils.show("授权成功");
            return true;
        }
        Utils.show("授权失败");
        return false;
    }

    public static boolean delete(String filePath) {
        return delete(getDocumentFile(OurygoApplication.getContext(), filePath));
    }

    public static boolean delete(DocumentFile documentFile) {
        if (documentFile != null && documentFile.exists()) {
            try {
                if (documentFile.isDirectory())
                    for (DocumentFile documentFile1 : documentFile.listFiles()) {
                        delete(documentFile1);
                    }
                return documentFile.delete();
            } catch (Exception e) {
                Log.e("FilePer", "失败错误" + e);
                return false;
            }
        }
        return true;
    }

    public static String toFilePath(DocumentFile documentFile){
        if (documentFile==null)
            return null;
        String uri=documentFile.getUri().toString();
        int strat=uri.indexOf(URI_ROOT_PREFIX);
        if (strat==-1)
            return null;

        String path=uri.substring(strat+URI_ROOT_PREFIX.length());
        path=path.replace("%2F","/");
        return path;
    }
}